package com.mbw.controller;

import com.mbw.common.utils.Result;
import com.mbw.common.utils.UserConstants;
import com.mbw.pojo.User;
import com.mbw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @PostMapping("/create")
    public Result createUser(@RequestBody User user){
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))){
            return Result.error().message("手机号已存在");
        }
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkUserNameUnique(user))){
            return Result.error().message("用户名已存在");
        }
        return userService.createUser(user);
    }

    
    @GetMapping("/hello")
    public String hello(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        return "Hello," + authentication.getName() + "!";
    }

    @GetMapping("/error")
    public String error(){
        return "403 error";
    }

    @GetMapping("/giao")
    public String giao() throws ExecutionException, InterruptedException {
        //创建Callable任务，并将其作为任务在单独线程上执行
        Callable<String> task = () ->{
            SecurityContext context = SecurityContextHolder.getContext();
            return context.getAuthentication().getName();
        };
        ExecutorService e = Executors.newCachedThreadPool();
        try{
            DelegatingSecurityContextCallable<String> contextTask = new DelegatingSecurityContextCallable<>(task);
            return "giao, " + e.submit(contextTask).get() + "!";
        }finally {
            e.shutdown();
        }
    }

    @GetMapping("/miao")
    public String miao() throws ExecutionException, InterruptedException {
        Callable<String> task = () ->{
            SecurityContext context = SecurityContextHolder.getContext();
            return context.getAuthentication().getName();
        };
        try{
            //在提交任务前DelegatingSecurityContextExecutorService会将安全上下文传播到执行此任务的线程
            return "miao, " + taskExecutor.submit(task).get() + "!";
        }finally {
            taskExecutor.shutdown();
        }
    }





}
